package org.fnzn.web.fngl;

import com.sun.corba.se.spi.ior.ObjectKey;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.fnzn.aop.SystemControllerLog;
import org.fnzn.bean.FnglCustomer;
import org.fnzn.bean.FnglProject;
import org.fnzn.bean.FnglStaff;
import org.fnzn.bean.FnglTurnover;
import org.fnzn.bean.statisbean.StatisWhere;
import org.fnzn.bean.vo.User;
import org.fnzn.core.Page;
import org.fnzn.core.Result;
import org.fnzn.service.FnglCustomerService;
import org.fnzn.service.FnglProjectService;
import org.fnzn.service.FnglStaffService;
import org.fnzn.util.CommonUtil;
import org.fnzn.util.DateTools;
import org.fnzn.util.ExcelUtil;
import org.fnzn.web.SysLogController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.Request;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 客户信息管理
 */
@Controller
@RequestMapping(value = "fnglCustomer")
@EnableAutoConfiguration
public class FnglCustomerController {
    Logger log = Logger.getLogger(SysLogController.class);
    
    @Autowired
    private FnglCustomerService fnglCustomerService;
    @Autowired
    private FnglProjectService fnglProjectService;
    @Autowired
    private FnglStaffService fnglStaffService;

    @RequestMapping(value = "/list",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    @ResponseBody
    @SystemControllerLog(description="查询客户")
    public Result findFnglCustomer(FnglCustomer fnglCustomer, Page page){
        return fnglCustomerService.findFnglCustomer(fnglCustomer,page);
    }

    @RequestMapping(value = "/commonlist",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    @SystemControllerLog(description="获取客户资源池")
    @ResponseBody
    public Result getFnglCommonCustomer(FnglCustomer fnglCustomer,Page page){
        return fnglCustomerService.getFnglCommonCustomer(fnglCustomer,page);
    }

    @RequestMapping(value = "/add",produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
    @SystemControllerLog(description="新增客户")
    @ResponseBody
    public Result insertFnglCustomer(FnglCustomer fnglCustomer){
        return  fnglCustomerService.insertFnglCustomer(fnglCustomer);
    }

    @RequestMapping(value = "/update",produces = "application/json;charset=UTF-8",method = RequestMethod.PUT)
    @SystemControllerLog(description="修改客户")
    @ResponseBody
    public Result updateFnglCustomer(FnglCustomer fnglCustomer){
        return  fnglCustomerService.updateFnglCustomer(fnglCustomer);
    }

    @RequestMapping(value = "/transfer",produces = "application/json;charset=UTF-8",method = RequestMethod.PUT)
    @SystemControllerLog(description="移交客户资源池中的客户")
    @ResponseBody
    public Result transferFnglCustomer(FnglCustomer fnglCustomer){
        User user = CommonUtil.getUser();
        return  fnglCustomerService.transferFnglCustomer(fnglCustomer,user);
    }

    @RequestMapping(value = "/{customerId}",produces = "application/json;charset=UTF-8",method = RequestMethod.DELETE)
    @SystemControllerLog(description="删除客户")
    @ResponseBody
    public Result deleteFnglCustomer(@PathVariable String customerId){
        return  fnglCustomerService.deleteFnglCustomer(customerId);
    }

    @RequestMapping(value = "/deleteAll",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    @SystemControllerLog(description="删除多个客户")
    @ResponseBody
    public Result deleteAllFnglCustomer(String Ids){
        return  fnglCustomerService.deleteAllFnglCustomer(Ids);
    }



    /**
     * 根据客户手机号获取到客户姓名
     */
    @RequestMapping(value = "/getCustomer/{phone}",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    @SystemControllerLog(description="根据客户手机号获取客户姓名")
    @ResponseBody
    public Result getCustomer(@PathVariable String phone){
        return fnglCustomerService.getCustomer(phone);
    }

    /**
     * 根据销售人员id获取到其所有客户所有手机号
     */
    @RequestMapping(value = "/getCustomerPhone",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    @SystemControllerLog(description = "根据销售人员id获取客户手机号")
    @ResponseBody
    public Result getCustomerPhone(String staffId){
        return fnglCustomerService.getCustomerPhone(staffId);
    }


    /**
     * 各个楼盘  客户总数，已成交客户数，未成交客户数
     */
    @RequestMapping(value = "/getProjectCustomer",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    @SystemControllerLog(description = "获取各个楼盘客户详情")
    @ResponseBody
    public Result getProjectCustomer(Page page){

        return fnglCustomerService.getProjectCustomer(page);
    }

    /**
     * 已成交客户数中  年龄阶段所占比例  年龄（30岁以下，30-50岁，50岁以上）
     */
    @RequestMapping(value = "/getCustomerAge",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    @SystemControllerLog(description = "获取各个楼盘已成交客户数中年龄阶段所占比例 ")
    @ResponseBody
    public Result getCustomerAge(Page page){

        return fnglCustomerService.getCustomerAge(page);
    }


    /**
     * 已成交客户按照区域、职业、是否贷款统计情况
     */
    @RequestMapping(value = "/getTurnOverCustomer",method = RequestMethod.GET)
    @SystemControllerLog(description = "获取各个楼盘已成交客户详情 ")
    @ResponseBody
    public Result getTurnOverCustomer(Page page,StatisWhere statisWhere){
        return fnglCustomerService.getTurnOverCustomer(page,statisWhere);
    }

    /**
     * 未成交客户 -- 依据客户意向面积、户型和类型 推荐楼盘
     */
    @RequestMapping(value = "/getUnTurnOver",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    @SystemControllerLog(description = "获取各个楼盘已成交客户数中年龄阶段所占比例 ")
    @ResponseBody
    public Result getUnTurnOver(Page page){

        return fnglCustomerService.getUnTurnOver(page);
    }

    /**
     * 每日录入客户分析
     */
    @RequestMapping(value = "/getEverydayCustomer",produces = "application/json;charset=UTF-8",method = RequestMethod.GET)
    @SystemControllerLog(description = "每日录入客户分析 ")
    @ResponseBody
    public Result getEverydayCustomer(Page page,StatisWhere statisWhere){

        return fnglCustomerService.getEverydayCustomer(page,statisWhere);
    }



    /**
     * 导出报表(客户管理中的数据)
     * @return
     */
    @RequestMapping(value = "/export")
    public void export(HttpServletRequest request, HttpServletResponse response, @RequestBody FnglCustomer fnglCustomer) throws Exception {
        //获取数据
        Result result = fnglCustomerService.exportFnglCustomer(fnglCustomer);
        List<FnglCustomer> list = (List<FnglCustomer>) result.getData();
        for (FnglCustomer item : list){
            // 根据项目id获取到项目名称
            FnglProject fnglProject = fnglProjectService.findById(item.getProjectId());
            item.setName(fnglProject.getName());
            // 根据销售人员id获取到销售姓名
            FnglStaff fnglStaff = fnglStaffService.findBy("staffId",item.getStaffId());
            item.setStaffName(fnglStaff.getRealName());
            // 根据意向面积字典值返回对应名称
            if(item.getIntentArea().equals("0")){
                item.setIntentArea("60平米以下");
            }
            if(item.getIntentArea().equals("1")){
                item.setIntentArea("60-90平米");
            }
            if(item.getIntentArea().equals("2")){
                item.setIntentArea("90-120平米");
            }
            if(item.getIntentArea().equals("3")){
                item.setIntentArea("120-140平米");
            }
            if(item.getIntentArea().equals("4")){
                item.setIntentArea("40平米以上");
            }
        }
        String[] title = {"销售姓名","手机号码","客户姓名","所属项目","意向面积","意向价格"};
        //excel文件名
        String fileName = "客户信息表"+DateTools.formatDate(new Date())+".xls";
        //sheet名
        String sheetName = "客户信息表";

        String[][] content;
        content = new String[list.size()][title.length] ;
        for (int i = 0; i < list.size(); i++) {
            FnglCustomer fnglCustomer1 = list.get(i);
            content[i][0] = fnglCustomer1.getStaffName();
            content[i][1] = fnglCustomer1.getPhone();
            content[i][2] = fnglCustomer1.getCustomerName();
            content[i][3] = fnglCustomer1.getName();
            content[i][4] = fnglCustomer1.getIntentArea();
            content[i][5] = fnglCustomer1.getIntentPrice();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        try {
            //设置response
            this.setResponseHeader(response, fileName);
            request.setAttribute("fileName",fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //响应到客户端
    }

    /**
     * 导出报表(客户资源池中的数据)
     * @return
     */
    @RequestMapping(value = "/exportCommon",produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
    @ResponseBody
    public void exportCommon(HttpServletRequest request, HttpServletResponse response, FnglCustomer fnglCustomer, Page page) throws Exception {
        //获取数据
        Result result = getFnglCommonCustomer(fnglCustomer,page);
        Page newPage = (Page) result.getData();
        List<?> rows = newPage.getRows();
        List<FnglCustomer> list = (List<FnglCustomer>) rows;
//        List<FnglCustomer> list = fnglCustomerService.getFnglCustomerUser();


        //excel标题
//        String[] title = {"销售姓名","客户姓名","录入时间","手机号码"};
        String[] title = {"销售姓名","手机号码","客户姓名","所属项目","意向面积","意向价格"};
        //excel文件名
        String fileName = "客户资源池信息表"+DateTools.formatDate(new Date())+".xls";
//        String fileName = "近一周内录入过客户的销售人员.xls";
        //sheet名
        String sheetName = "客户资源池信息表";

        String[][] content;
        content = new String[list.size()][title.length] ;
        for (int i = 0; i < list.size(); i++) {
            FnglCustomer fnglCustomer1 = list.get(i);
//            content[i][0] = fnglCustomer1.getStaffName();
//            content[i][1] = fnglCustomer1.getCustomerName();
//            content[i][2] = DateTools.formatDate(fnglCustomer1.getCreateTime());
            content[i][1] = fnglCustomer1.getPhone();
//            content[i][4] = fnglCustomer1.getTurnoverFlag();
//            content[i][5] = fnglCustomer1.getKnowWay();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);

            //os.write(wb.getBytes( ));
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //响应到客户端
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            fileName = URLEncoder.encode(fileName,"UTF-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
